package com.zjlp.im.netty.client;

import com.zjlp.im.netty.handler.DefaultClientHandler;
import com.zjlp.im.netty.handler.DefaultHttpClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;


/**
 * Created by Administrator on 2016/12/8.
 */
public class EchoHttpClient {
    public void initHttpClient() {
        Bootstrap clientBootstarap=new Bootstrap();
        NioEventLoopGroup workGroup=new NioEventLoopGroup();
        clientBootstarap.group(workGroup);
        clientBootstarap.channel(NioSocketChannel.class);
        clientBootstarap.handler(new LoggingHandler(LogLevel.INFO));
        clientBootstarap.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline=ch.pipeline();
                pipeline.addLast("http-response",new HttpResponseDecoder());
                pipeline.addLast("http-request",new HttpRequestEncoder());
                pipeline.addLast("http-default",new DefaultHttpClientHandler(workGroup));
            }
        });
        ChannelFuture clientFuture=clientBootstarap.connect(new InetSocketAddress("localhost", 17878));
        clientFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()){
                    //建立连接了，发送服务端消息
                    DefaultFullHttpRequest request=new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.POST,"/file/upload");
                    request.content().writeBytes("我是客户端的请求信息".getBytes());
                    clientFuture.channel().writeAndFlush(request);
                    System.out.println("给客户端发送消息成功！");
                }
            }
        });
        try {
            clientFuture.sync().awaitUninterruptibly();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        EchoHttpClient client=new EchoHttpClient();
        client.initHttpClient();
    }
}
